#!/bin/python
#coding:utf8
'''
Created on 2011-6-6

@author: mark
'''

import web
from config import database
from config import memcache_client
from model import problem

db = database
mc = memcache_client

def getCommentsByPid(pid):
    key = str("comments_pid_%s" % pid)
    comments = mc.get(key)
    if not comments:
        comments = _getCommentsByPid(pid)
        if comments:
            mc.set(key, comments)
    return comments

def _getCommentsByPid(pid):
    comments = db.select(['comment','user'], where="comment.commenter = user.uid and comment.pid = %s " % pid, order="comment.create_time asc")
    if comments:
        return comments
    else:
        return []

def addComment(_pid, _content):
    current_user = web.ctx.session['current_user']
    uid = -1 if not current_user else current_user['uid']
    res = db.insert("comment", content=_content, pid=_pid, commenter=uid)
    if res:
        return problem.addCommentCountByPid(_pid)


def getNewComment(count):
    comments = db.select(['comment', 'user'], where="user.uid = comment.commenter", order="comment.create_time desc", limit=count)
    def cutHtml(comment):
        comment.pdesc = "".join(comment.content[0:100])
        return comment
    
    return [cutHtml(comment) for comment in comments]